package com.zxy.controller;


import com.zxy.common.result.PageResult;
import com.zxy.common.result.Result;
import com.zxy.pojo.entity.BusinessRecord;
import com.zxy.pojo.entity.CustomerClue;
import com.zxy.pojo.dto.BusinessQueryDTO;
import com.zxy.pojo.vo.AssignmentVo;
import com.zxy.pojo.vo.CustomerDetailVO;
import com.zxy.service.ClueService;
import com.zxy.service.OpportunityService;
import com.zxy.util.OperLog;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 商机管理
 */
@RestController
@RequestMapping("/business")
@Slf4j
public class OpportunityController {
    @Autowired
    private OpportunityService opportunityService;

    @Autowired
    private ClueService clueService;

    /**
     * 分页查询商机列表
     */
    @OperLog(title = "分页查询商机列表", businessType = 0, saveParams = true)
    @GetMapping("/list")
    public Map<String, Object> list(BusinessQueryDTO query) {
        try {
            PageResult pageResult = opportunityService.listByPage(query);
            Map<String, Object> result = new HashMap<>();
            result.put("total",pageResult.getTotal());
            result.put("rows",pageResult.getRows());
            result.put("code", 200);
            result.put("msg", "查询成功");
            result.put("params", null);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, Object> errorResult = new HashMap<>();
            errorResult.put("code", 500);
            errorResult.put("msg", "查询失败：" + e.getMessage());
            errorResult.put("params", null);
            return errorResult;
        }
    }


    /**
     * 添加商机
     * @param customerClue
     * @return
     */
    @OperLog(title = "新增商机", businessType = 1, saveParams = true, saveResult = true)
    @PostMapping
    public Result add(@RequestBody CustomerClue customerClue){
        return opportunityService.saves(customerClue) ? Result.success() : Result.error("添加失败");
    }


    /**
     * 商机池
     * @param query
     * @return
     */
    @OperLog(title = "商机池分页查询", businessType = 0, saveParams = true)
    @GetMapping("/pool")
    public Map<String, Object> poolList(BusinessQueryDTO query) {
        try {
            PageResult pageResult = opportunityService.listByPage(query);
            Map<String, Object> result = new HashMap<>();
            result.put("total", pageResult.getTotal());
            result.put("rows", pageResult.getRows());
            result.put("code", 200);
            result.put("msg", "查询成功");
            result.put("params", null);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, Object> errorResult = new HashMap<>();
            errorResult.put("code", 500);
            errorResult.put("msg", "查询失败：" + e.getMessage());
            errorResult.put("params", null);
            return errorResult;
        }
    }

    /**
     * 显示历史沟通记录
     * @return
     */
    @OperLog(title = "查询商机历史沟通记录", businessType = 0, saveParams = true)
    @GetMapping("/record/list")
    public Map<String, Object> list(@RequestParam Long businessId) {
        List<BusinessRecord> data = opportunityService.getListByBusinessId(businessId);

        Map<String, Object> result = new HashMap<>();
        result.put("code", 200);
        result.put("msg", "操作成功");
        result.put("data", data);
        return result;
    }

    /**
     * 查询所有客户资料
     * @param id
     * @return
     */
    @OperLog(title = "查询商机客户资料详情", businessType = 0, saveParams = true)
    @GetMapping("/{id}")
    public Result listAll(@PathVariable  Long id){
        CustomerDetailVO cdv = opportunityService.getByIds(id);
        if (cdv != null) {
            return Result.success(cdv);
        } else {
            return Result.error("未找到指定客户");
        }
    }


    /**
     * 添加沟通记录
     * @param record
     * @return
     */
    @OperLog(title = "新增商机沟通记录", businessType = 1, saveParams = true, saveResult = true)
    @PostMapping("/record")
    public Result record(@RequestBody BusinessRecord record){
        log.info("添加沟通记录：{}", record);

        boolean success = opportunityService.addRecord(record);
        if (success) {
            // 如果需要返回创建的记录信息，可以查询刚插入的记录
            // 这里假设BusinessRecord有一个getId()方法
            return Result.success("添加成功");
        } else {
            return Result.error("添加失败");
        }
    }

    /**
     * 分配商机
     * @param assignmentVo
     * @param request
     * @return
     */
    @OperLog(title = "分配商机", businessType = 2, saveParams = true, saveResult = true)
    @PutMapping("/assignment")
    public Result assignment(@RequestBody AssignmentVo assignmentVo, HttpServletRequest request){
        log.info("分配线索，参数: {}", assignmentVo);
        // 从session中获取当前操作用户名
        String currentUsername = (String) request.getSession().getAttribute("username");
        if (currentUsername == null) {
            currentUsername = "admin"; // 默认值
        }
        String result = opportunityService.assignment(assignmentVo.getIds(), assignmentVo.getUserId());

        // 可以根据返回结果判断是否成功
        if (result.contains("成功分配")) {
            return Result.success(result);
        } else {
            return Result.error(result);
        }
    }


    /**
     * 系统通知商机列表查询
     */
    @OperLog(title = "系统通知商机列表查询", businessType = 0, saveParams = true)
    @GetMapping("/system/notice/list")
    public Result<PageResult> lists(@RequestParam Map<String, Object> params) {
        try {
            // 将Map参数转换为BusinessQueryDTO对象
            BusinessQueryDTO query = new BusinessQueryDTO();
            if (params.get("pageNum") != null) {
                query.setPageNum(Integer.parseInt(params.get("pageNum").toString()));
            }
            if (params.get("pageSize") != null) {
                query.setPageSize(Integer.parseInt(params.get("pageSize").toString()));
            }
            // 设置其他可能的查询参数
            query.setName((String) params.get("name"));
            query.setOwner((String) params.get("owner"));

            PageResult pageResult = opportunityService.listByPage(query);
            return Result.success(pageResult);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 回退操作接口
     * @param id 业务ID
     * @param type 操作类型
     * @return
     */
    @OperLog(title = "商机操作回退", businessType = 2, saveParams = true, saveResult = true)
    @PutMapping("/back/{id}/{type}")
    public Result backOperation(@PathVariable Long id, @PathVariable Integer type) {
        try {
            // 执行回退操作
            boolean result = opportunityService.backOperation(id, type);
            if (result) {
                return Result.success(1); // 返回成功标识
            } else {
                return Result.error("操作失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("操作异常：" + e.getMessage());
        }
    }

    /**
     * 捞取商机接口
     * @return
     */
    @OperLog(title = "捞取商机", businessType = 2, saveParams = true, saveResult = true)
    @PutMapping("/gain")
    public Result gainBusiness(@RequestBody Map<String, Object> request) {
        log.info("捞取商机请求参数: {}", request);

        // 获取商机ID
        List<?> idsList = (List<?>) request.get("ids");
        Long id = Long.parseLong(idsList.get(0).toString());

        log.info("捞取商机，商机ID: {}", id);
        return opportunityService.gainBusiness(id);
    }


    /**
     * 上传合同接口
     * @param id
     * @return
     */
    @OperLog(title = "商机上传合同", businessType = 2, saveParams = true, saveResult = true)
    @PutMapping("/contract/changeContract/{id}")
    public Result changeContract(@PathVariable Long id){
        opportunityService.changeContract(id);
        return Result.success();

    }
}